package com.peng.authority;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
@Component
public class MyAuthorityPermitImp implements MyAuthorityPermit {

    @Override
    public boolean hasAuthority(HttpServletRequest request, Authentication authentication) {
        String[] roles = request.getParameterValues("roles");
        String[] authorities = request.getParameterValues("authorities");
        System.out.println("获取权限集合" + authentication.getAuthorities());
        System.out.println("身份：" + authentication.getPrincipal());
        System.out.println("凭证" + authentication.getCredentials());
        System.out.println("明细：" + authentication.getDetails());
        System.out.println("是否登录" + authentication.isAuthenticated());
        if (roles != null) {
            for (String role : roles) {
                String temp = "ROLE" + role;
                //判断用户权限集合中是否包含当前请求路径需要的权限
                if (authentication.getAuthorities().contains(new SimpleGrantedAuthority(temp))) {
                    //登录用户有权限
                    return true;
                }
                ;
            }
        }
        if (authorities != null) {
            for (String authority : authorities) {
                //判断资源权限
                if (authentication.getAuthorities().contains(new SimpleGrantedAuthority(authority))) {
                    return true;
                }
            }
        }
        return false;
    }
}
